//
//  PublishIssueTopicViewController.m
//  LookScore
//
//  Created by wws on 2018/1/18.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//
#import "MBProgressHUD+MJ.h"
#import "PublishIssueBottomView.h"
#import "UITextView+Placeholder.h"
#import "PublishIssueTopicViewController.h"
#import "LSXPopMenu.h"
#import "ACSelectMediaView.h"
#import "LSPubulishTopicCell.h"
#import "LSPublishModel.h"
#import "LSPubulishMatchViewController.h"
#import "LSPubulishBottomReusableView.h"
@interface PublishIssueTopicViewController ()<UITextViewDelegate,LSXPopMenuDelegate,UICollectionViewDelegate,UICollectionViewDataSource>{
  
    PublishIssueBottomView *_issueBottomView;//底部工具选择视图
    UITextView          *_inputTextView;//文本输入框
    UILabel * _bottomLabel;
    NSMutableArray * imgArray;
    UIButton * tmpBtn;
    
}
@property (nonatomic,strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSMutableArray * modelArray;


@end

@implementation PublishIssueTopicViewController

- (NSMutableArray *)modelArray{
    if (!_modelArray) {
        _modelArray = @[].mutableCopy;
    }
    
    return _modelArray;
}

-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
        flowLayout.minimumLineSpacing=0;
        flowLayout.minimumInteritemSpacing=0;
        flowLayout.itemSize=CGSizeMake(LSScreenWidth/2,LSAutoVlaue(50, LSScreenWidth));
        _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0,0, LSScreenWidth,LSScreenHeight -64) collectionViewLayout:flowLayout];
        //        _collectionView.userInteractionEnabled=YES;
        //        flowLayout.headerReferenceSize = CGSizeMake(LSScreenWidth, 50);
        flowLayout.footerReferenceSize = CGSizeMake(LSScreenWidth, LSAutoVlaue(50, LSScreenWidth));
        _collectionView.backgroundColor=[UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.title=@"发布话题";
    self.view.backgroundColor=Color(236, 240, 244);
    
    //加入子视图
    [self addIssueTopicSubviews];
    [self loadData];
    // Do any additional setup after loading the view.
}

- (void)loadData{
    [LSHttpEnclosureTool GET:LSMatchHotInTopic parameters:nil resBlock:^(id responseObject) {
        if (responseObject) {
            for (NSDictionary * dict in responseObject[@"TodayHotMatchList"]) {
                LSPublishModel * model = [LSPublishModel mj_objectWithKeyValues:dict];
                [self.modelArray addObject:model];
            }
//            MyLog(@"%@",responseObject);
        }
        
        [self.collectionView reloadData];
    }];
    
    
}

/*加入子视图*/
-(void)addIssueTopicSubviews{
    
    //容器view
    UIView *bgView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, LSScreenWidth, LSAutoVlaue(180, LSScreenWidth))];
    bgView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:bgView];
    
    //文本输入框
    NSInteger leftPadding=8;
    UITextView *inputTextView=[[UITextView alloc]initWithFrame:CGRectMake(leftPadding, leftPadding,LSScreenWidth-leftPadding*2,50)];
    inputTextView.showsVerticalScrollIndicator=YES;
    inputTextView.returnKeyType   = UIReturnKeyDefault;
    inputTextView.backgroundColor   =   [UIColor whiteColor];
    inputTextView.placeholder=@"和大家分享一下吧...";
    [inputTextView setTextColor:[UIColor blackColor]];
    inputTextView.placeholderColor=Color(148, 148, 148);
    inputTextView.delegate=self;
    _inputTextView=inputTextView;
    [inputTextView setFont:[UIFont systemFontOfSize:15]];
    [bgView addSubview:inputTextView];
    
    
    ACSelectMediaView * mediaView = [[ACSelectMediaView alloc] initWithFrame:CGRectMake(25, inputTextView.maxY, LSScreenWidth-LSScareValue(50, LSScreenWidth), 1)];
    mediaView.type = ACMediaTypePhotoAndCamera;
    mediaView.maxImageSelected = 9;
    mediaView.naviBarBgColor = LSNavMainColor;
    mediaView.rowImageCount =  3;
    mediaView.lineSpacing = 5;
    mediaView.interitemSpacing = LSScareValue(15, LSScreenWidth);
    mediaView.sectionInset = UIEdgeInsetsMake(LSScareValue(15, LSScreenWidth), LSScareValue(15, LSScreenWidth), LSScareValue(15, LSScreenWidth), LSScareValue(15, LSScreenWidth));
//    UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
    [mediaView observeViewHeight:^(CGFloat mediaHeight) {
        
    }];
    
    [bgView addSubview:mediaView];
    bgView.height = mediaView.maxY;
    [mediaView observeSelectedMediaArray:^(NSArray<ACMediaModel *> *list) {
        imgArray = @[].mutableCopy;
        for (ACMediaModel * model in list) {
            [imgArray addObject:model.image];
        }
        bgView.frame = CGRectMake(0, 0, LSScreenWidth, mediaView.maxY + 20);
        self.collectionView.frame = CGRectMake(0, bgView.maxY, LSScreenWidth, LSScreenHeight - bgView.maxY);
    }];
    UILabel * bottomLabel = [[UILabel alloc] init];
    bottomLabel.textAlignment = NSTextAlignmentRight;
    bottomLabel.textColor=LSTitleGrayColor2;
    bottomLabel.font = LSFontSize12;
    bottomLabel.text = @"0/800";
    [bgView addSubview:bottomLabel];
    
    _bottomLabel = bottomLabel;
    bottomLabel.sd_layout
    .rightSpaceToView(bgView, 10)
    .bottomSpaceToView(bgView, 0)
    .heightIs(20);
    [bottomLabel setSingleLineAutoResizeWithMaxWidth:180];
    MyLog(@"%f",mediaView.maxY);
    
    
    //右边的发布确认按钮
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(publishIssueSender:)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} forState:UIControlStateNormal];
    
    
    if (self.pushType == 1) {
        
    }else{
        self.collectionView.frame = CGRectMake(0, bgView.maxY, LSScreenWidth, LSScreenHeight - bgView.maxY);
        [self.collectionView registerClass:[LSPubulishBottomReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView"];
        [self.collectionView registerNib:[UINib nibWithNibName:@"LSPubulishTopicCell" bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([LSPubulishTopicCell class])];
        [self.view addSubview:self.collectionView];
    }
    
    

    
}
#pragma mark--collentionDelegate & dataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.modelArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LSPubulishTopicCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LSPubulishTopicCell class]) forIndexPath:indexPath];
    if (!cell) {
       cell = [[NSBundle mainBundle] loadNibNamed:@"LSPubulishTopicCell" owner:self options:nil].firstObject;
    }
    cell.model = self.modelArray[indexPath.row];
    cell.block = ^(UIButton *btn){
        [self btnClick:btn withIndexRow:indexPath];
    };
    cell.selectedBackgroundView = [UIView new];
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    LSPubulishBottomReusableView * footerView;
    
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footerView" forIndexPath:indexPath];
        footerView.block = ^(UIButton *sender) {
            if (sender.tag == 1001) {
                LSPubulishMatchViewController * puVC = [[LSPubulishMatchViewController alloc] init];
                puVC.block = ^(NSInteger MacthId) {
                    _selectMatchId = MacthId;
                };
                [self.navigationController pushViewController:puVC animated:YES];
            }else{
                tmpBtn.selected = NO;
                [tmpBtn setBackgroundColor:LSTitleWhiteColor];
                _selectMatchId = 0;
            }
        };
    }else{
        footerView = [LSPubulishBottomReusableView new];
    }
    return footerView;

}
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//
//    return CGSizeMake(LSScreenWidth, LSAutoVlaue(50, LSScreenWidth));
//
//}



- (void)btnClick:(UIButton *)sender withIndexRow:(NSIndexPath *)indexPath{
    tmpBtn.selected = NO;
    [tmpBtn setBackgroundColor:LSTitleWhiteColor];
    tmpBtn = sender;
    [sender setBackgroundColor:Color(210,210,210)];
    sender.selected = YES;

    LSPublishModel * model = self.modelArray[indexPath.row];
    _selectMatchId = model.MatchId;
}

/*右边的发布确认按钮*/
-(void)publishIssueSender:(UIBarButtonItem *)sender{
    
    if([[_inputTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        [MBProgressHUD showOnlyMessage:@"发布的内容不能全是空格" afterDelay:1.5];
        return;
    }
    if (_inputTextView.text.length > 0) {
        if (imgArray.count != 0) {
            [LSHttpEnclosureTool Upload:LSUSERUPLOADIMG parameters:@{@"type":@"1"} uploadParamArray:imgArray resBlock:^(id responseObject) {
                if (responseObject) {
                    
                    [self releaseTopicWithImgStr:responseObject];
                }
            }];
        }else{
            
            [self releaseTopicWithImgStr:@""];
        }
        
    }else{
        
        [MBProgressHUD showOnlyMessage:@"请输入发布的内容" afterDelay:1.5];
        
    }
    
    
}

- (void)releaseTopicWithImgStr:(NSString *)imgStr{
    NSDictionary * dict = @{@"circleId":@(self.circleId),@"cid":[LSAccountArchive account].Cid,@"content":_inputTextView.text,@"imgUrlStr":imgStr,@"matchId":@(_selectMatchId)};
    MyLog(@"%@",dict);
    [LSHttpEnclosureTool POST:LSTOPICPUBLISH parameters:dict resBlock:^(id responseObject) {
        [MBProgressHUD showOnlyMessage:@"发布成功" afterDelay:1.5];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            if (self.block) {
//                self.block();
//            }
            [notifiCenter postNotificationName:@"LOADCIRCLEDATA" object:nil];
            
            
            [self.navigationController popViewControllerAnimated:YES];
        });
    }];
    
}

/*底部点击事件*/
-(void)issueBottomViewToolTapTag:(NSInteger)tag{
     [LSXPopMenu showAtPoint:CGPointMake(self.view.centerX, self.view.centerY - 64) titles:@[@"  拍摄",@"  从相册选择"] icons:nil menuWidth:200 isShowTriangle:NO delegate:self];
}

-(void)LSXPopupMenuDidSelectedAtIndex:(NSInteger)index LSXPopupMenu:(LSXPopMenu *)LSXPopupMenu{
    
    MyLog(@"------点击---%ld",(long)index);
}
#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView{
    
    NSString *inputText=textView.text;
    _bottomLabel.text = [NSString stringWithFormat:@"%zd/%d",inputText.length,KWordsMaxXNumber];
//    _issueBottomView.wordsNumber=inputText.length;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    NSString *inputString=[textView.text stringByReplacingCharactersInRange:range withString:text];
    
    if (inputString.length>KWordsMaxXNumber) {
        
        NSString *msg=[NSString stringWithFormat:@"字数不能超过%d",KWordsMaxXNumber];
        [MBProgressHUD showOnlyMessage:msg afterDelay:1.5f];
        
        return NO;
    }else{
        return YES;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
